package com.shaoshaohuo.app.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

/**
 * Created by Administrator on 2017/7/11.
 */

public class SelfadaptionImageview extends ImageView {
    public SelfadaptionImageview(Context context) {
        super(context);
    }

    public SelfadaptionImageview(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public SelfadaptionImageview(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setImageDrawable(@Nullable Drawable drawable) {
        super.setImageDrawable(drawable);
        selfBitmap();
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        selfBitmap();
    }

    @Override
    public void setImageResource(@DrawableRes int resId) {
        super.setImageResource(resId);
        selfBitmap();
    }

    public void selfBitmap(){
        Drawable drawable = getDrawable();
        if(drawable==null){
            return;
        }
        BitmapDrawable newd= (BitmapDrawable) drawable;
        if(newd.getBitmap()==null){
            return;
        }
        Bitmap bitmap = newd.getBitmap();
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int widthPixels = getResources().getDisplayMetrics().widthPixels;
        if(width<widthPixels){
            float i = (float) widthPixels / (float) width;
            ViewGroup.LayoutParams layoutParams = getLayoutParams();
            layoutParams.width=widthPixels;
            layoutParams.height = (int) (height * i);
        }else {
            int i = widthPixels / width;
            ViewGroup.LayoutParams layoutParams = getLayoutParams();
            layoutParams.width= WindowManager.LayoutParams.MATCH_PARENT;
            layoutParams.height= WindowManager.LayoutParams.WRAP_CONTENT;
             Log.e("TAG", "selfBitmap: 大于宽度" );
        }


    }
}
